﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace StarUtils.Extension
{
    public static partial class StringExtension
    {

        /// <summary>
        /// 字符串首字母小写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FirstLowercase(this string str)
        {
            if (str.IsNullOrWhiteSpace())
            {
                return str;
            }
            str = str.Trim().First().ToString().ToLower() + str[1..];
            return str;
        }
        /// <summary>
        /// 获取压缩的html内容
        /// </summary>
        /// <param name="inputbs"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string GetNUglifyStr(byte[] inputbs, string contentType)
        {
            if (inputbs == null || !inputbs.Any())
            {
                return string.Empty;
            }
            var deHtml = System.Text.Encoding.UTF8.GetString(inputbs);
            if (!contentType.Contains("text/html"))
                return deHtml;

            return deHtml.GetNUglifyStr();
        }

        public static string GetNUglifyStr(this string input)
        {

            try
            {
                if (input.IsNullOrWhiteSpace())
                {
                    return string.Empty;
                }
                if (input.Contains("<<"))
                {
                    input = input.Replace("<<", "&lt;&lt;");
                }
                if (input.Contains(">>"))
                {
                    input = input.Replace(">>", "&gt;&gt;");
                }

                var minResult = NUglify.Uglify.Html(input);

                if (minResult.HasErrors)
                {
                    return input;
                }
                return minResult.Code;
            }
            catch
            {

                return input;
            }


        }

        /// <summary>
        /// Truncates string so that it is no longer than the specified number of characters.
        /// </summary>
        /// <param name="str">String to truncate.</param>
        /// <param name="length">Maximum string length.</param>
        /// <returns>Original string or a truncated one if the original was too long.</returns>
        public static string Truncate(this string str, int length)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0");
            }

            if (str.IsNullOrWhiteSpace())
            {
                return null;
            }

            int maxLength = Math.Min(str.Length, length);
            return str.Substring(0, maxLength);
        }

        public static bool BytesCompareBase64(byte[] b1, byte[] b2)
        {
            if (b1 == null || b2 == null) return false;
            if (b1.Length != b2.Length) return false;
            return string.Compare(Convert.ToBase64String(b1), Convert.ToBase64String(b2), false) == 0;
        }


        /// <summary>
        /// 把Cas号转化成cas url形式
        /// </summary>
        /// <param name="casNo"></param>
        /// <returns></returns>
        public static string ToCasUrl(this string casNo)
        {
            if (casNo.IsNullOrEmpty()) return "";
            return casNo.Trim().Replace("-", String.Empty);
        }

        /// <summary>
        /// 验证cas号是否是正确的
        /// </summary>
        /// <param name="cass"></param>
        /// <returns></returns>
        public static bool IsCas(this string cass)
        {
            if (cass.IsNullOrEmpty()) return false;
            cass = cass.Replace("–", "-");
            Regex r = new Regex("^[0-9]{2,7}-[0-9]{2}-[0-9]$");
            Match m = r.Match(cass);
            bool rv = false;
            if (m.Success)
            {
                string teststr = cass.Substring(0, cass.LastIndexOf('-'));
                string lastchar = cass.Replace(teststr, "").Replace("-", "");
                teststr = teststr.Replace("-", "");

                int total = 0;
                for (int i = 0; i < teststr.Length; i++)
                {
                    total += int.Parse(teststr.Substring(i, 1)) * (teststr.Length - i);
                }
                int mod = total % 10;
                if (lastchar == mod.ToString())
                {
                    rv = true;
                }
            }
            return rv;
        }



        public static T SafeValue<T>(this T? value) where T : struct
        {
            return value.GetValueOrDefault();
        }

        public static string Description(this System.Enum instance)
        {
            return EnumHelper.GetDescription(instance.GetType(), instance);
        }


        public static bool IsMatch(this string value, string pattern)
        {
            if (value == null)
            {
                return false;
            }

            return Regex.IsMatch(value, pattern);
        }

        public static bool IsMatch(this string value, string pattern, RegexOptions options)
        {
            if (value == null)
            {
                return false;
            }

            return Regex.IsMatch(value, pattern, options);
        }

        public static string GetMatch(this string value, string pattern)
        {
            if (value.IsNull())
            {
                return string.Empty;
            }

            return Regex.Match(value, pattern).Value;
        }

        public static IEnumerable<string> GetMatchingValues(this string value, string pattern)
        {
            if (value.IsNull())
            {
                return new string[0];
            }

            return value.GetMatchingValues(pattern, RegexOptions.None);
        }

        public static IEnumerable<string> GetMatchingValues(this string value, string pattern, RegexOptions options)
        {
            return from Match match in value.GetMatches(pattern, options)
                   where match.Success
                   select match.Value;
        }

        public static MatchCollection GetMatches(this string value, string pattern, RegexOptions options)
        {
            return Regex.Matches(value, pattern, options);
        }

        public static void ForEach<T>(this IEnumerable<T> ts, Action<T> action)
        {
            foreach (T t in ts)
            {
                action(t);
            }
        }
    }


    public static class JsonExtensions
    {
        public static T ToObject<T>(this string json)
        {
            return JsonHelper.ToObject<T>(json);
        }

        public static string ToJson(this object target, bool isConvertToSingleQuotes = false, bool camelCase = false, bool indented = false)
        {
            return JsonHelper.ToJson(target, isConvertToSingleQuotes, camelCase, indented);
        }
    }
}
